package com.example.finalproject;

import com.example.finalproject.User.User;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class LoginInterceptor implements HandlerInterceptor {

    private boolean isLoggedIn(HttpServletRequest request) {
        // 判断用户是否已登录，这里可以根据实际逻辑进行判断
        HttpSession session = request.getSession();
        User login_User = (User) session.getAttribute("login_User");
        if (login_User != null) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        if (!isLoggedIn(request)) {
            // 未登录，重定向到登录页面
            response.sendRedirect(request.getContextPath() + "/pre_login");
            return false; // 拦截请求
        }
        return true; // 放行请求
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        // 在请求处理之后、视图渲染之前执行，可以对 ModelAndView 进行操作
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        // 在请求完成后执行，可以进行资源清理操作
    }
}
